package com.peng.leetcode.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * GenerateTrees2
 * 95. 不同的二叉搜索树 II
 * https://leetcode.cn/problems/unique-binary-search-trees-ii/
 *
 * @author: lupeng6
 * @create: 2023/2/20 14:19
 */
public class GenerateTrees2 {

    public List<TreeNode> generateTrees(int n) {
        if (n == 0) {
            return new ArrayList<>();
        }
        return generate(1, n);
    }

    private List<TreeNode> generate(int start, int end) {
        List<TreeNode> allTrees = new ArrayList<>();
        if (start > end) {
            allTrees.add(null);
            return allTrees;
        }
        for (int i = start; i <= end; i++) {
            List<TreeNode> l = generate(start, i - 1);
            List<TreeNode> r = generate(i + 1, end);
            for (TreeNode ln : l) {
                for (TreeNode rn : r) {
                    TreeNode root = new TreeNode(i);
                    root.left = ln;
                    root.right = rn;
                    allTrees.add(root);
                }
            }
        }
        return allTrees;
    }
}
